package com.hmdp.utils;


import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 分布式主键生成
 */
@Component
public class RedisIdWorker {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    /**
     * 开始时间戳
     * 从1970.1月.1日.0时.0分.0秒开始到2022.1.1.0.0.0
     */
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    /**
     * 序列号位数
     */
    private static final int COUNT_BITS = 32;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix){

        //1.生成时间
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond-BEGIN_TIMESTAMP;

        //2.生成序列号
        //2.1获取当前日期，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        //System.out.println("timestamp:" + timestamp);
        //2.2自增长 这里加上日期是因为如果一直用一个key的话，redis的存储自增数有上限，所以一天换一个key 返回一个自增后的值
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        //System.out.println("count:" + count);

        //
        return timestamp << COUNT_BITS | count;


    }

    public static void main(String[] args) {

    }
}
